package cn.snorlaxzjt.LBSserver.controller;

import com.qiniu.storage.UploadManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

public class FileController {




    // 读取配置文件中的路径 static/files
    @Value("${fileLocation}")
    private String fileLocation;

    @PostMapping("upload")
    @ResponseBody
    public void upload(MultipartFile file) throws IOException {
        // 获得 classpath 的绝对路径
        String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;
        File newFile = new File(realPath);
        // 如果文件夹不存在、则新建
        if (!newFile.exists()) newFile.mkdirs();
        // 上传
        Date date = new Date();
        String fileName = date.getTime() +"@" + file.getOriginalFilename();
        file.transferTo(new File(newFile, fileName));
    }

    @Value("${fileLocation}")

    @GetMapping("download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        // 获得待下载文件所在文件夹的绝对路径
        String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;
        // 获得文件输入流
        FileInputStream inputStream = new FileInputStream(new File(realPath, fileName));
        // 设置响应头、以附件形式打开文件
        response.setHeader("content-disposition", "attachment; fileName=" + fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        int len = 0;
        byte[] data = new byte[1024];
        while ((len = inputStream.read(data)) != -1) {
            outputStream.write(data, 0, len);
        }
        outputStream.close();
        inputStream.close();
    }



}
